<!DOCTYPE html>
<html lang="zh-cn">

<head>
    <meta charset="utf-8" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"
    />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <title>14. 最长公共前缀</title>
  </head>

<body>
  <!-- start -->
  <div>https://leetcode.cn/problems/longest-common-prefix/description/</div>
  <!-- end -->
</body>
<!-- js start -->
<script type="text/javascript">
  /**
   * @param {string[]} strList
   * @return {string}
   */
  var longestCommonPrefix = function (strList) {

    // 只有一个数据，直接返回
    if (strList.length === 1) {
      return strList[0]
    }

    let minTestList = [];

    // 寻找最短的字符
    strList.map(item => {
      const firstItemInTest = minTestList[0];

      // 测试数组中没有数据，则加入
      if (minTestList.length === 0) {
        return minTestList = [item]
      }

      // 当前长度小于测试长度，则丢弃原有测试数据
      if (item.length < firstItemInTest.length) {
        minTestList = [item]
      }

      // 与测试数据长度相等，则加入
      if (item.length === firstItemInTest.length) {
        if (!minTestList.includes(item)) minTestList.push(item)
      }
    })

    console.log(`[minTestList]`, minTestList)
    // debugger

    if (!minTestList.length) return ''

    return findLonger(strList, minTestList)
  };

  function findLonger(strList, minTestList) {
    let target = null;

    minTestList.map(tItem => {
      if (strList.every(strItem => tItem === strItem.slice(0, tItem.length))) {
        target = tItem;
      }
    });

    if (target !== null) return target;

    if (minTestList[0].length === 1) return '';

    let nowLength = minTestList[0].length;
    minTestList = minTestList.map(item => {
      let res = item.slice(0, nowLength - 1)

      return res
    });

    return findLonger(strList, minTestList);
  }

  console.log(longestCommonPrefix(["flower", "flow", "flight"]));

</script>

</html>
